package util;

import java.io.File;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import org.junit.Test;

public class Email {
	
	
	/**
	 * 简单邮件
	 * @throws Exception
	 */
	@Test
	public void emaliTest() throws Exception {
		
		
		for(int i=0;i<10;i++){
		
		/**
		 *1.得到Session
		 */
		Properties props=new Properties();
		props.setProperty("mail.host", "smtp.163.com");
		props.setProperty("mail.smtp.auth", "true");
		
		Authenticator auth=new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication(){
				return new PasswordAuthentication("jiabaoyu6","liu123");
			}
		};
		
		Session session=Session.getInstance(props, auth);
		
		/**
		 * 创建MimeMessage
		 */
		MimeMessage msg=new MimeMessage(session);
		msg.setFrom(new InternetAddress("jiabaoyu6@163.com"));
		msg.setRecipients(RecipientType.TO,"849319996@qq.com");
		msg.setRecipients(RecipientType.CC,"1218800603@qq.com");
		msg.setRecipients(RecipientType.CC,"987366988@qq.com");
		
		msg.setSubject("这是来自刘浩的测试邮件");
		msg.setContent("你好鬼帅啊","text/html;charset=utf-8");
		
		/**
		 * 发送
		 */
		Transport.send(msg);

		}
}
	
	
	
	/**
	 * 带附件的邮件
	 * @throws Exception
	 */
	@Test
	public void emaliTest2() throws Exception {
		
		
		/**
		 *1.得到Session
		 */
		Properties props=new Properties();
		props.setProperty("mail.host", "smtp.163.com");
		props.setProperty("mail.smtp.auth", "true");
		
		Authenticator auth=new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication(){
				return new PasswordAuthentication("jiabaoyu6","liu123");
			}
		};
		
		Session session=Session.getInstance(props, auth);
		
		/**
		 * 创建MimeMessage
		 */
		MimeMessage msg=new MimeMessage(session);
		msg.setFrom(new InternetAddress("jiabaoyu6@163.com"));
		msg.setRecipients(RecipientType.TO,"849319996@qq.com");

		
		msg.setSubject("这是来自刘浩的测试邮件");
		
		/**
		 * 创建多部分主体
		 */
		MimeMultipart list=new MimeMultipart();
		
		//创建MimeBodyPart
		MimeBodyPart part1=new MimeBodyPart();
		part1.setContent("刘浩测试邮件，带附件","text/html;charset=utf-8");
		
		list.addBodyPart(part1);
		
		//创建MimeBodyPart
		MimeBodyPart part2=new MimeBodyPart();
		
		//设置附件内容
		part2.attachFile(new File("c:/A.txt"));
		part2.setFileName(MimeUtility.encodeText("小说.txt"));
		list.addBodyPart(part2);
		
		
		
		//把多部分主体作为邮件内容
		msg.setContent(list);
		
		
		/**
		 * 发送
		 */
		Transport.send(msg);
		
	}

}
